package bean;

import java.io.IOException;
import java.net.ConnectException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.mysql.jdbc.Connection;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import DAO.AvaliacaoAntropometricaDAO;
import DAO.HemodialiseDAO;
import DAO.PacienteDAO;
import DAO.RelatoriosDAO;
import Utils.Conexao;
import Utils.Uteis;

public class RelatorioCheckupBean {
	private Date dataInicial;
	private Date dataFinal;
	
	public Date getDataInicial() {
		return dataInicial;
	}
	
	public void setDataInicial(Date dataInicial) {
		this.dataInicial = dataInicial;
	}
	
	public Date getDataFinal() {
		return dataFinal;
	}
	
	public void setDataFinal(Date dataFinal) {
		this.dataFinal = dataFinal;
	}
	
	public void gerarRelatorio()
	{
		try {			
			String file = FacesContext.getCurrentInstance().getExternalContext().getRealPath("jasper/relatorioCheckup.jasper");				 
			String diretorio = FacesContext.getCurrentInstance().getExternalContext().getRealPath("jasper") + "/";				 
			Connection con = (Connection) Conexao.getConection();
			
			Map<String, Object> parameters = new HashMap<String, Object>();
			parameters.put("data_inicial", this.dataInicial);
			parameters.put("data_final", this.dataFinal);			
			parameters.put("SUBREPORT_DIR", diretorio);	
			
			byte[] bytes = null;
			ServletOutputStream outpustream = null;
			
			JasperPrint print = JasperFillManager.fillReport(file, parameters, con);			
			bytes = JasperExportManager.exportReportToPdf(print);
			
			FacesContext context = FacesContext.getCurrentInstance();  
			HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();			
			
			response.setContentType("application/pdf");  
			response.setHeader("Content-Disposition","attachment; filename=\"relatorioCheckup.pdf\"");  
			outpustream = response.getOutputStream();
			outpustream.write(bytes, 0, bytes.length);
			
			outpustream.flush();  
			outpustream.close();			
			
		}catch (JRException e) {
			e.printStackTrace();		
		} catch(IOException e) {
			e.printStackTrace();
		}
		
	}
}
